package com.ktjy.ktmall.servlet;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.ktjy.ktmall.entity.AjaxResult;
import com.ktjy.ktmall.entity.BannerItem;
import com.ktjy.ktmall.entity.User;
import com.ktjy.ktmall.service.BannerItemService;
import com.ktjy.ktmall.service.impl.BannerItemServiceImpl;
import com.ktjy.ktmall.util.UploadAliYunUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

// 用于接收并处理轮播图相关的请求
@WebServlet(name = "BannerItemServlet", urlPatterns = "/uni/home/banner")
public class BannerItemServlet extends HttpServlet {
    BannerItemService service = null;
    @Override
    public void init(ServletConfig config) throws ServletException {
        service = new BannerItemServiceImpl();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String opr = request.getParameter("opr");
        AjaxResult result = null;  // 创建后端返回值封装类对象
        if ("list".equals(opr)) {
            Integer type = Integer.valueOf(request.getParameter("type"));
            // 根据跳转类型获取轮播图数据列表数据
            List<BannerItem> list = service.findByType(type);
            result = AjaxResult.success("轮播图列表加载成功!", list);
        }else if ("insert".equals(opr)) {
            String params = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            JSONObject entries = JSONUtil.parseObj(params);
            BannerItem bannerItem = entries.get("bannerItem", BannerItem.class);
            int count = service.insert(bannerItem);
            if (count > 0) {
                result = AjaxResult.success("新增成功!");
            } else {
                result = AjaxResult.success("新增失败!");
            }
        }else if("delete".equals(opr)){
            Integer id = Integer.valueOf(request.getParameter("id"));
            // 根据跳转类型获取轮播图数据列表数据
            int count = service.delete(id);
            result = AjaxResult.success("轮播图列表删除成功!", count);
        }
        PrintWriter outPrint = response.getWriter();
        // 将result对象转换成JSON字符串再响应到小程序端
        outPrint.print(JSONArray.toJSONString(result));
        outPrint.flush();
        outPrint.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    public void destroy() {
        service = null;
    }
}
